/*
@Time : 2021/2/5 10:22
@Author : 吴周海
@Mail: wzh200x@126.com
@File : message.go
@Software: GoLand
*/
package game

import (
	"GameApiServer/utils"
	"encoding/base64"
	"encoding/json"
	"github.com/beego/beego/v2/core/logs"
	"math/rand"
	"strconv"
	"time"
)

const (
	MD5SECRETKEY = "BBe6O82s4gSU" // MD5加密字符串
)

func FormatMessage(api string, msgData []interface{}, key string, sid string) *GameApiMessage {
	// 数据序列化JSON
	jData, err := json.Marshal(msgData)
	if err != nil {
		logs.Error("FormatMessage msdData json Error:", api)
		return nil
	}
	//重置随机种子
	rand.Seed(time.Now().UnixNano())
	// 生成随机加密addkey值 (2到9)
	addkey := rand.Intn(7) + 2
	// 加密偏移
	secretChar := rune(8)
	// 拼接
	addKeySecretStr := strconv.Itoa(addkey*78) + string(secretChar)
	encodeB64Str := base64.StdEncoding.EncodeToString(jData)
	//创建加密字符数组
	newSecretDataStr := ""
	dLength := len(encodeB64Str)
	//数据偏移
	cutTimes := 1 // 截取字符串的次数
	for i := 0; i < dLength; i += addkey * 1 {
		// 截取字符串
		moveStr := ""
		if dLength-i > addkey {
			moveStr = encodeB64Str[i : addkey*cutTimes]
		} else {
			moveStr = encodeB64Str[i:]
		}
		// 拼接
		newSecretDataStr = moveStr + newSecretDataStr
		// 次数+1
		cutTimes += 1
	}
	// 拼接加密key信息
	secretContent := addKeySecretStr + newSecretDataStr
	// 创建消息结构体
	msg := NewGameApiMessage(api, sid, key, secretContent)
	// 格式化消息加密字符串
	SignInfo := SignFormat(msg)

	// 进行MD5加密
	msg.Sign = utils.Md5Encode(SignInfo)
	logs.Debug("加密字符串" + SignInfo)
	logs.Debug("加密串" + msg.Sign)
	return msg
}

func SignFormat(apiMsg *GameApiMessage) string {
	signStr := ""
	signStr += apiMsg.Api + apiMsg.Sid + apiMsg.MessageKey + apiMsg.MessageData + strconv.FormatInt(apiMsg.Tm, 10) + MD5SECRETKEY
	return signStr
}
